package com.tydic.daily.utils;

import java.io.*;
import java.util.*;

public class PropertiesUtils {

    public static Properties loadPropertiesFile(String fileName) {

        Properties prop = new Properties();
        if(fileName != null && !"".equals(fileName.trim())) {
            fileName = fileName.trim();
            InputStream is = PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName);
            if (is == null) {
                TapLogger.logger().warn("the file [" + fileName + "] can not be found in classpath");
                return prop;
            }
            Properties tempPro = new Properties();

            try {
                tempPro.load(is);
                for (Object o : tempPro.keySet()) {
                    prop.put(o.toString().replace('|',':'), tempPro.get(o));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

            return prop;
    }

    /**
     * 保存属性信息到文件
     *
     * @param properties
     *      原属性信息
     * @param targetFile
     *      目标文件
     * @param handler
     *      对过此handler可以对键和值进行额外的处理，参考{@link cn.wind.utils.spring.PropertiesUtils.EntryHandler}
     * @param comment
     *      保存到目标文件时，文件中的头注释
     * @throws IOException
     *      访问文件时，可能会出现此异常
     */
    public static void storeToFile(Properties properties, File targetFile, EntryHandler handler, String comment) throws IOException {

        Properties finalProperties = new Properties();
        if (handler != null) {

            Set<String> propertyNames = properties.stringPropertyNames();
            for (String propertyName : propertyNames) {
                String value = properties.getProperty(propertyName);
                finalProperties.put(handler.handleProperty(propertyName), handler.handlePropertyValue(value));
            }
        } else {
            // 不需要对键值进行处理，则使用原Properties即可
            finalProperties = properties;
        }

        finalProperties.store(new FileOutputStream(targetFile), comment);
    }

    /**
     * 属性处理类
     */
    public static abstract class EntryHandler {

        /**
         * 对键值进行处理
         *
         * @param value
         * @return
         */
        public abstract Object handlePropertyValue(String value);

        /**
         * 对键进行处理
         *
         * @param propertyName
         * @return
         */
        public abstract Object handleProperty(String propertyName);
    }
}
